package cn.buk.qms.service;

import cn.buk.common.JsonResult;
import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.tms.dao.DetrDao;
import cn.buk.tms.dto.DetrInfoDto;
import cn.buk.tms.entity.misc.DetrInfo;
import cn.buk.common.util.DateUtil;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yfdai
 */
@Component
public class DetrServiceImpl extends BaseAbstractService implements DetrService {

	private final Logger logger = LogManager.getLogger(DetrServiceImpl.class);

	@Autowired
	private DetrDao detrDao;
	

	@Override
  public List<DetrInfoDto> searchDetrInfos(final int enterpriseId, CommonSearchCriteria sc) {
		List<DetrInfo> detrInfos = detrDao.search(enterpriseId, sc);

		List<DetrInfoDto> dtos = new ArrayList<>();
		for(DetrInfo detrInfo: detrInfos) {
			DetrInfoDto dto = new DetrInfoDto();
			BeanUtils.copyProperties(detrInfo, dto, "flights");

			dtos.add(dto);
		}


		return dtos;
	}

  @Override
  public JsonResult refreshDetrInfo(int enterpriseId, int id) {
		int retCode = detrDao.refreshDetrInfo(enterpriseId, id);

		return JsonResult.createJsonResult(retCode);
  }

  @Override
	public JsonResult createDetrRequestByExcel(int enterpriseId, String fileName) {
		List<DetrInfo> list = new ArrayList<>();

		try {
			File target = new File(fileName);
			FileInputStream fi = new FileInputStream(target);
			Workbook wb = create(fi);

			importDetrRequest(enterpriseId, list, wb);
		} catch (Exception ex) {
			logger.error(ex.getMessage());
		}

		if (list.size() == 0) {
			return JsonResult.createJsonResult(-1, "没有数据");
		}


		int retCode = detrDao.createDetrInfo(list);

		return JsonResult.createJsonResult(retCode);
	}

	/**
	 * 格式1的excel导入
	 * 票号，销售日期（可选）
	 * 数据从第二行开始
	 */
	private void importDetrRequest(final int enterpriseId, List<DetrInfo> list, Workbook wb) {
		Sheet sheet = wb.getSheetAt(0);
		final int rowNum = sheet.getLastRowNum() + 1;

		for (int i = 1; i < rowNum; i++) {
			Row row = sheet.getRow(i);

			//票号
			final String ticketNo = row.getCell(0).getStringCellValue().trim().toUpperCase();

			if (ticketNo == null || ticketNo.length() < 13 || ticketNo.length() > 14) {
        continue;
      }

			Cell cell = row.getCell(1);

			final String ddate;
			if (cell != null) {
        ddate = cell.getStringCellValue().trim().toUpperCase();
      } else {
        ddate = "";
      }


			DetrInfo o = new DetrInfo();
			o.setEnterpriseId(enterpriseId);

			final String ticketNo0 = ticketNo.length() == 14 ? ticketNo: ticketNo.substring(0, 3) + "-" + ticketNo.substring(3);

			o.setTicketNo(ticketNo0);


			Date fdDate = DateUtil.getTomorrowDate();

			try {
				if (ddate != null && ddate.length() == 10) {
          fdDate = DateUtil.convertToDate(ddate, "yyyy-MM-dd");
        }
			} catch (Exception e) {
				logger.error(e.getMessage());
			}

			o.setSellDate(fdDate);

			list.add(o);
		}
	}

}
